package net.flowas.secure;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import net.flowas.secure.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class DemoRealm extends AuthorizingRealm {
 
	//private String persistenceUnitName;
	
	private EntityManager em;
	    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
    	UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        //User user = userDao.findUser(upToken.getUsername());
        String jpql="select o from User as o where o.email = '"+upToken.getUsername()+"' and o.password = '"+new String((char[])upToken.getCredentials())+"'";
        User user =(User)em.createQuery(jpql).getSingleResult();
        if (user == null) {
            throw new AuthenticationException("用户名或密码不正确！");
        }
        return new SimpleAccount(user, token.getCredentials(), getName());
    }
   
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	System.out.println("================================");
                Object shiroUser = principals.getPrimaryPrincipal();
		//User user = userDao.findUserByLoginName(shiroUser.loginName);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//info.addRoles(user.getRoleList());                
		return info;
    }


    /**
     * 依賴注入的變量
     * @param persistenceUnitName
     */
	public void setPersistenceUnitName(String persistenceUnitName) {
		//this.persistenceUnitName = persistenceUnitName;
		if(persistenceUnitName ==null){
			persistenceUnitName="cartPU";
		}
		em= Persistence.createEntityManagerFactory (persistenceUnitName).createEntityManager();
	}
    
}
